import express from 'express'
import TokenTools from '#utils/token.js'
import { resError, resAuthError } from '#utils/res.js'
import { notCheckTokenApis } from '#config'
import { AuthError } from '#utils/error.js'
import { db, TABLE } from '#utils/dbconf.js'
import { SQL_ERROR_LIST } from '../server.config.js'
import 'express-async-errors'
// 引入路由
import userRoute from '#routes/user.js'
import toolsRoute from '#routes/tools.js'
import wsRoute from '#routes/ws.js'

const router = express()

// // 所有请求日志
// router.use(async (req, {}, next) => {
//   const { originalUrl: api, method, headers, connection } = req
//   const ip = headers['x-real-ip'] || connection.remoteAddress || ''
//   const ua = headers['user-agent'] || ''
//   const referer = headers['referer'] || ''
//   db.table(TABLE.USER).add({ api, method, ip, ua, referer })
//   if (!referer) throw new AuthError() // api工具
//   next()
// })

// // 请求拦截 - token验证
// router.use((req, res, next) => {
//   const token = TokenTools.getToken(req)
//   const { originalUrl: api, method } = req
//   try {
//     const { id, auth, mail } = TokenTools.check(token)
//     res.locals = { id, auth, mail }
//   } catch (error) {
//     const _url = method + api
//     const deCheck = notCheckTokenApis.some((url) => _url.includes(url))
//     if (deCheck) return next()
//     else throw new AuthError()
//   }
//   next()
// })

//路由
router.use('/user', userRoute)
router.use('/tools', toolsRoute)
router.use('/ws', wsRoute)

// 全局异常处理
router.use((err, req, res, next) => {
  if (err) {
    const { message, name } = err
    switch (name) {
      case 'AuthError':
        return res.send(resAuthError())
      case 'DataEmptyError':
        return res.send(resError('目标数据为空'))
      case 'Error':
        for (let sqlError of SQL_ERROR_LIST)
          if (message.includes(sqlError.key)) return res.send(resError(sqlError.value))
      default:
        return res.send(resError(message))
    }
  }
})

export default router
